import {Button, Input, message, Modal, Popconfirm, Space, Table} from "antd";
import React, {useContext, useState} from "react";
import axios from "axios";
import {hostContext} from "../../store/commonContext.jsx";
import cookie from "js-cookie";


const CategoryModal = ({
                           visible,
                           onCancel,
                           categoryList,
                           setCategoryList,
                           fetchCategoryList
                       }) => {

    const buttonContentStyle = {
        display: 'flex'
    }

    /*按钮的上下间距*/
    const buttonMarginStyle = {
        marginTop: 0,
        marginBottom: 10,
        marginLeft: 'auto'
    }

    const categoryOptionsStyle = {
        display: 'flex'
    }

    const categoryButtonStyle = {
        marginLeft: 5
    }

    const host = useContext(hostContext)
    const token = cookie.get('access_token')
    const userId = cookie.get('user_id')
    const requestHeader = {headers: {'Authorization': 'Bearer ' + token}}

    const handleDeleteCategory = async (id) => {
        const response = await axios.get(`${host}/category/delete-category/${id}`, requestHeader)
        if ('200' === response.data.status) {
            message.success('删除成功')
        }
        setTimeout(() => location.reload(), 500)
    }

    const [editingKey, setEditingKey] = useState(''); // 当前编辑行唯一标识
    const [tempData, setTempData] = useState({});     // 临时存储编辑数据
    const [tempList, setTempList] = useState([]) //新增前的数组
    // 切换编辑状态
    const editCategory = (record) => {
        setEditingKey(record.key)
        // 存储原始数据快照
        setTempData(record)
    }
    // 保存修改
    const saveCategory = async () => {
        // 保存接口
        const response = await axios.post(host + '/category/save-category', tempData, requestHeader)
        // 保存完后清空编辑状态和临时数据，防止下次新增会默认使用上一次的数据
        setEditingKey('')
        setTempData({})
        await fetchCategoryList()
    }
    // 更新临时数据
    const handleChange = (value, field) => {
        setTempData({...tempData, userId: userId, [field]: value})
    };
    // 取消编辑
    const handleCancel = () => {
        setEditingKey('')
        setTempData([])
        // 这里是防止没有点击新增，点击编辑后点击取消，会把数据清空，或者没有分类的时候，点击新增后，无法取消
        setCategoryList(categoryList.length === 1 && categoryList[0].id === '' ? [] : (tempList.length === 0 ? categoryList : tempList))
    }

    // 新增一行
    const handleAddCategory = () => {
        // 确保每次只能点击一次新增，(为什么？因为我想)
        console.log(categoryList.length)
        console.log("categoryList", categoryList)
        console.log("tempList", tempList)
        const newCategory = {
            id: '',
            value: '',
            label: '',
            key: '',
            new: true
        }
        if (categoryList.length === 0){
            setTempList([])
            setCategoryList(preList => [newCategory, ...preList])
        } else if (categoryList[0].id !== '') {
            setTempList(categoryList)
            setCategoryList(preList => [newCategory, ...preList])
        }
    }

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: '4vw',
        },
        {
            title: 'value值',
            dataIndex: 'value',
            key: 'value',
            width: '8vw',
            render: (text, record) => {
                return editingKey === record.key ? (
                    <Input
                        value={tempData.value || ''}
                        onChange={e => handleChange(e.target.value, 'value')}
                    />
                ) : text
            }
        },
        {
            title: '分类',
            dataIndex: 'label',
            key: 'label',
            width: '8vw',
            render: (text, record) => {
                return editingKey === record.key ? (
                    <Input
                        value={tempData.label || ''}
                        onChange={e => handleChange(e.target.value, 'label')}
                    />
                ) : text
            }
        },
        {
            title: '操作',
            dataIndex: 'options',
            key: 'options',
            width: '12vw',
            render: (_, record) => (
                <div style={categoryOptionsStyle}>
                    {record.new === true ? (<></>) : (<Popconfirm
                        title='注意'
                        description='确定要删除该分类吗？'
                        onConfirm={() => handleDeleteCategory(record.id)}
                        okText='确定'
                        cancelText='取消'
                    >
                        <Button
                            key="cancel"
                            danger
                            variant='outlined'
                            size={"small"}
                            style={categoryButtonStyle}
                        >
                            删除
                        </Button>
                    </Popconfirm>)}
                    {editingKey === record.key ? (
                        <div style={categoryOptionsStyle}>
                            <Button
                                variant='outlined'
                                size={"small"}
                                style={categoryButtonStyle}
                                onClick={handleCancel}
                            >
                                取消
                            </Button>
                            <Popconfirm
                                title='提示'
                                description='确定要修改此分类吗？'
                                onConfirm={saveCategory}
                                okText='确定'
                                cancelText='取消'>
                                <Button
                                    variant='outlined'
                                    size={"small"}
                                    style={categoryButtonStyle}
                                >
                                    保存
                                </Button>
                            </Popconfirm>
                        </div>
                    ) : (
                        <Button
                            variant='outlined'
                            size={"small"}
                            style={categoryButtonStyle}
                            onClick={() => editCategory(record)}
                            disabled={!!editingKey}
                        >
                            编辑
                        </Button>
                    )}
                </div>
            )
        }
    ]


    return (
        <Modal
            title="配置列表"
            visible={visible}
            onCancel={onCancel}
            style={{maxWidth: 720}}
            footer={[
                <Button key="back"
                        onClick={onCancel}
                        type="primary"
                >
                    确定
                </Button>,
            ]}
        >
            <div style={buttonContentStyle}>
                <Button
                    style={buttonMarginStyle}
                    type="primary"
                    onClick={handleAddCategory}
                >
                    新增
                </Button>
            </div>
            <Table
                columns={columns}
                dataSource={categoryList}
                bordered
                size={"small"}
            />
        </Modal>
    )
}


export default CategoryModal;